package com.iot08.admin.service;

import com.iot08.admin.service.page.PageVO;
import com.iot08.admin.service.page.PageableImpl;
import com.iot08.common.constant.Const;
import com.iot08.common.entity.admin.Channel;
import com.iot08.common.entity.admin.SysUser;
import com.iot08.common.entity.app.DeviceModels;
import com.iot08.common.entity.app.EntryRecord;
import com.iot08.common.service.base.BaseService;
import com.iot08.common.utils.CollectionUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.xmlbeans.impl.xb.xsdschema.Public;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: Weichao
 * @Date: 2024/07/31/11:46
 * @Description:
 */
@Slf4j
@Service
public class DeviceModelsService extends BaseService<DeviceModels> {

    @Resource
    private DeviceService deviceService;
    @Resource
    private OperationService operationService;
    public Page<DeviceModels> list(PageVO page, String s_agentId, String s_devModelId, SysUser user) {
        PageableImpl pageable = new PageableImpl();
        page.setSort(Sort.by(Sort.Order.desc("modifytime")));
        pageable.setPage(page);

        Criteria criteria = new Criteria();
        // delete 不为 1
        criteria.and("delete").ne(1);
        if (StringUtils.isNotEmpty(s_devModelId)) {
            criteria.and("id").is(s_devModelId);
        }else if (StringUtils.isNotEmpty(s_agentId)) {
            criteria.and("vender").is(s_agentId);
        }
        if (user.getType() == Const.CHANNELUSER_TYPE) {
            criteria.orOperator(Criteria.where("agent").in(CollectionUtil.longToStr(user.getChannelAff().getChannelCodes())),
                    Criteria.where("agent").exists(false));
        }
        Query query = new Query().addCriteria(criteria);
        long count = mongoTemplate.count(query, DeviceModels.class);
        page.setTotalResult((int) count);
        List<DeviceModels> list = mongoTemplate.find(query.with(pageable), DeviceModels.class);
        return new PageImpl<DeviceModels>(list, pageable, count);
    }
    public Boolean del(String devModelId, SysUser user, String IP, String modelName) {
        try{
            //不删除, 标记 delete == 1
            //delById(devModelId)
            updateById(devModelId, new Update().set("delete", 1));
            //添加日志
            operationService.add(user, IP, Const.OPERATION_DELETE, "设备型号删除", null,"型号删除", "型号删除: "+modelName, null, null, null);
            return true;
        }catch (Exception e){
            log.error("设备型号删除失败: "+ IP, e);
            return false;
        }
    }


    public Integer updateDevModel(DeviceModels devModel, SysUser user, String IP) {
        DeviceModels oldModels = this.findById(devModel.getId());
        devModel.setModifytime(new Date());
        //只显示表示
        try {
            Update update = new Update();
            if(devModel.getVideo_modelid() != null){
                update.set("video_modelid", devModel.getVideo_modelid());
            }
            if(devModel.getModel() != null){
                update.set("model", devModel.getModel());
            }
            if(devModel.getVender() != null){
                update.set("vender", devModel.getVender());
            }
            //venderName
            if(devModel.getVenderName() != null){
                update.set("venderName", devModel.getVenderName());
            }
            if(devModel.getModules() != null){
                update.set("modules", devModel.getModules());
            }
            if(StringUtils.isNotEmpty(devModel.getVipEnjoyAlone())){
                update.set("vipEnjoyAlone", devModel.getVipEnjoyAlone());
            } else {
                update.set("vipEnjoyAlone","");
            }

            if(StringUtils.isNotEmpty(devModel.getPlaceHomePage())){
                update.set("placeHomePage", devModel.getPlaceHomePage());
            }
            if(devModel.getAll_funtion_des() != null){
                update.set("all_funtion_des", devModel.getAll_funtion_des());
            }
            //isWatchCustomFunction
            if(devModel.getIsWatchCustomFunction() != null){
                update.set("isWatchCustomFunction", devModel.getIsWatchCustomFunction());
            }
            //opfind
            if(devModel.getOpfind() != null){
                update.set("opfind", devModel.getOpfind());
            }else{
                update.set("opfind", 0);
            }
            if(devModel.getOpdialswitch() != null){
                update.set("opdialswitch", devModel.getOpdialswitch());
            }else{
                update.set("opdialswitch", 0);
            }
            if(devModel.getDataFlow() != null){
                update.set("dataFlow", devModel.getDataFlow());
            }else{
                update.set("dataFlow", 0);
            }
            if(devModel.getCostFlow() != null){
                update.set("costFlow", devModel.getCostFlow());
            }else{
                update.set("costFlow", 0);
            }
            if(devModel.getOpFlower() != null){
                update.set("opFlower", devModel.getOpFlower());
            }else{
                update.set("opFlower", 0);
            }
            if(devModel.getOpSchoolTimeTable() != null){
                update.set("opSchoolTimeTable", devModel.getOpSchoolTimeTable());
            }else{
                update.set("opSchoolTimeTable", 0);
            }
            if(devModel.getOpVoucherCenter() != null){
                update.set("opVoucherCenter", devModel.getOpVoucherCenter());
            }else{
                update.set("opVoucherCenter", 0);
            }
            if(devModel.getOpHeartRate() != null){
                update.set("opHeartRate", devModel.getOpHeartRate());
            }else{
                update.set("opHeartRate", 0);
            }
            if(devModel.getOpTemperature() != null){
                update.set("opTemperature", devModel.getOpTemperature());
            }else{
                update.set("opTemperature", 0);
            }
            if(devModel.getOpTimingSwitch() != null){
                update.set("opTimingSwitch", devModel.getOpTimingSwitch());
            }else{
                update.set("opTimingSwitch", 0);
            }
            if(devModel.getNavigationmodules() != null){
                update.set("navigationmodules", devModel.getNavigationmodules());
            }
            if(devModel.getPpmfmodules() != null){
                update.set("ppmfmodules", devModel.getPpmfmodules());
            }
            if(devModel.getOpDicpenCloudType() != null){
                update.set("opDicpenCloudType", devModel.getOpDicpenCloudType());
            }
            if(devModel.getIsDevIMEIShort() != null){
                update.set("isDevIMEIShort", devModel.getIsDevIMEIShort());
            }
            if(devModel.getPositioningTimeInterval() != null){
                update.set("positioningTimeInterval", devModel.getPositioningTimeInterval());
            }
            //modifytime
            update.set("modifytime", new Date());
            updateById(devModel.getId(), update);
            if(!oldModels.getModules().equals(devModel.getModules()) || !oldModels.getModel().equals(devModel.getModel())){
                //更新设备集合
                deviceService.updateDeviceModels(devModel.getModel(),devModel.getModules(),devModel.getId());
            }
            //添加日志
            operationService.add(user, IP, Const.OPERATION_UPDATE, "设备型号修改", null,"型号修改", "型号修改: "+devModel.getModel(), null, null, null);
        }catch (Exception e){
            log.error("设备型号修改失败: "+ IP, e);
            return 2;
        }
        return 0;
    }
    public DeviceModels save(DeviceModels devModel, SysUser user, String IP) {
        devModel.setCreater(user.getId());
        devModel.setCreatetime(new Date());
        devModel.setModifytime(new Date());
        //添加日志
        operationService.add(user, IP, Const.OPERATION_ADD, "设备型号创建", null,"型号创建", "型号创建: "+devModel.getModel(), null, null, null);
        return save(devModel);
    }
    /***
     * @Description: 设备型号 查重
     * @Param: [id, model]
     * @return: java.lang.Boolean false: 已存在 true: 不存在
     * @Author: Weichao
     * @Date: 2024/7/31
     */
    public Boolean check(String id, String model) {
        Criteria criteria = new Criteria();
        // delete 不为 1
        criteria.and("delete").ne(1);
        if (StringUtils.isNotEmpty(id)) {
            criteria.and("_id").is(id);
        }
        if (StringUtils.isNotEmpty(model)) {
            criteria.and("model").is(model);
        }
        Query query = new Query().addCriteria(criteria);
        long count = mongoTemplate.count(query, DeviceModels.class);
        if (count > 0) {
            return false; //已存在
        }else{
            return true; //不存在
        }
    }
    //updateNum
    public void updateNum(DeviceModels devModel, Integer num) {
        devModel.setImport_num(devModel.getImport_num() + num);
        updateById(devModel.getId(), new Update().set("import_num", devModel.getImport_num()));
    }
    public void updateNumJop() {
        Query query = new Query(Criteria.where("deleted").is(0));
        List<DeviceModels> devMList = this.find(query);
        for (DeviceModels devM : devMList) {
            //model_id
            long importNum = deviceService.countByModelId(devM.getId());
            long activeNum = deviceService.countActiveNumByModelId(devM.getId());
            Update update = new Update().set("import_num", importNum).set("active_num", activeNum);
            this.updateById(devM.getId(), update);
        }
    }
}
